package restful

import (
	"encoding/json"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/ferror"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/gins"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/gorms"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/https"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/resultcode"
	"gitee.com/shiqiyue/xd-bi/internal/modules/cr/model"
	"github.com/gin-gonic/gin"
)

// 获取报表-返回参数
type GetReportResult struct {
	// 展示格式
	DisplayType int `json:"display_type"`
	// 分页支持
	PageSupport bool `json:"page_support"`
	// 表单信息
	Forms []GetReportResultForm `json:"forms"`
	// 返回结果
	Results []GetReportResultColumn `json:"results"`
	// 是否显示合计
	ShowSummary bool `json:"show_summary"`
}

// 获取报表-返回参数-表单信息
type GetReportResultForm struct {
	// 表单名称
	FormName string `json:"form_name"`
	// 类型
	FormType int `json:"form_type"`
	// 属性名称
	AttributeName string `json:"attribute_name"`
	//  字典
	Dicts []DictInfo `json:"dicts"`
	// 额外配置
	ExtraConfig *string `json:"extra_config"`
	// 顺序
	IndexNum *int `json:"index_num"`
	// 默认值
	DefaultValue *string `json:"default_value"`
	// 是否必填
	Required bool `json:"required"`
	// 查询报表编号
	QueryReportCode *string `json:"query_report_code"`
}

// 获取报表-返回参数-返回信息信息
type GetReportResultColumn struct {
	// 名称
	ResultName string `json:"result_name"`
	// 类型
	ResultType int `json:"result_type"`
	// 属性名称
	AttributeName string `json:"attribute_name"`
	// isShow
	IsShow bool `json:"is_show"`
	// 额外配置
	ExtraConfig *string `json:"extra_config"`
	// 顺序
	IndexNum *int `json:"index_num"`
	// 空值字体颜色
	EmptyValueFontColor *string `json:"empty_value_font_color"`
	// 空值颜色
	EmptyValue *string `json:"empty_value"`
	// 字体颜色
	FontColor *string `json:"font_color"`

	// 是否跳转
	IsJump bool `json:"is_jump"`
	// 跳转类型
	JumpType *int `json:"jump_type"`
	// 跳转目标
	JumpTarget *string `json:"jump_target"`
	// 跳转参数
	JumpParams []*GetReportResultColumnJumpParam `json:"jump_params"`
	// 跳转方式
	JumpMode *int `json:"jump_mode"`
}

type GetReportResultColumnJumpParam struct {
	// 参数类型
	ParamType int `json:"param_type"`
	// 参数名称
	Name string `json:"name"`
	// 值
	Value string `json:"value"`
}

// 字典信息
type DictInfo struct {
	// 名称
	Text string `json:"text"`
	// 值
	Value interface{} `json:"value"`
}

/**
@api {get} /bi/public/:code 根据编号获取报表信息
@apiSampleRequest http://192.168.3.132:9102/
@apiName 获取报表信息
@apiGroup 报表

@apiParam {String} code 报表编号

@apiSuccess {String} msg 返回消息
@apiSuccess {String} code 返回编号
@apiSuccess {Object} data 返回数据

@apiSuccess {Number} data.display_type 展示类型 ,1-列表,2-分页
@apiSuccess {Boolean} data.page_support 是否支持分页，如果为true，则请求报表时候，需要额外加上currentPage和pageSize入参

@apiSuccess {Object[]} data.forms 表单数组
@apiSuccess {String} data.forms.form_name 表单名称(中文)
@apiSuccess {Number} data.forms.form_type 表单类型,1-文字输入框,2-数字输入框,3-日期输入框,4-select选择器
@apiSuccess {String} data.forms.attribute_name 属性名称，请求报表时候的入参
@apiSuccess {String} data.forms.extra_config 额外配置
@apiSuccess {String} data.forms.index_num 顺序
@apiSuccess {Object[]} data.forms.dicts 字典列表
@apiSuccess {String} data.forms.dicts.text 字典的中文介绍
@apiSuccess {Number} data.forms.dicts.value 字典的值
@apiSuccess {Number} data.forms.dicts.query_report_no 查询报表编号


@apiSuccess {Object[]} data.results 报表返回结果信息数组
@apiSuccess {String} data.results.result_name 返回信息名称(中文)
@apiSuccess {Number} data.results.result_type 返回信息类型, 1-文本，2-Date，3-Time，4-DateTime，5-字典，6-数字，7-百分比
@apiSuccess {String} data.results.attribute_name 属性名称
@apiSuccess {Boolean} data.results.is_show 是否展示
@apiSuccess {String} data.results.extra_config 额外配置
@apiSuccess {Number} data.results.index_num 顺序
@apiSuccess {String} data.results.empty_value_font_color 空值字体颜色
@apiSuccess {String} data.results.empty_value 空值颜色
@apiSuccess {String} data.results.font_color 字体颜色
@apiSuccess {Boolean} data.results.is_jump 是否跳转
@apiSuccess {Number} data.results.jump_type 跳转类型,1-报表,2-链接(系统内), 3-外部链接
@apiSuccess {String} data.results.jump_target 跳转目标
@apiSuccess {Number} data.results.jump_mode 跳转方式,1-对话框,2-标签
@apiSuccess {Object[]} data.results.jump_params 跳转参数

@apiSuccess {Number} data.results.jump_params.param_type 参数类型,1-固定值，2-返回字段
@apiSuccess {String} data.results.jump_params.name 参数名称
@apiSuccess {String} data.results.jump_params.value 值






@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{
  "msg": "请求成功",
  "code": 200,
  "data": {
    "display_type": 2,
    "page_support": true,
    "forms": [
      {
        "form_name": "机构名称",
        "form_type": 1,
        "attribute_name": "organization_name"
      },
      {
        "form_name": "机构类别",
        "form_type": 2,
        "attribute_name": "organization_category"
      }
    ],
    "results": [
      {
        "result_name": "organization_id",
        "result_type": 1,
        "attribute_name": "organization_id"
      },
      {
        "result_name": "name",
        "result_type": 1,
        "attribute_name": "name"
      }
    ]
  }
}
*/
func (h *Handlers) GetReport(c *gin.Context) {
	db := gorms.GetDb(c, h.Db)
	code := c.Param("code")
	if code == "" {
		gins.Err(c, ferror.NewWithCode("报表编号为空", resultcode.PARAM_REQUIRED), https.StatusInternalServerError)
		return
	}
	report := model.Report{}
	err := h.ReportSrv.GetByCode(c, db, code, &report)
	if err != nil {
		gins.Err(c, ferror.WrapWithCode("报表获取失败", resultcode.FAIL, err), https.StatusInternalServerError)
		return
	}
	reportForms, err := h.ReportFormSrv.GetByReportId(c, db, report.ReportId)
	if err != nil {
		gins.Err(c, ferror.WrapWithCode("报表参数获取失败", resultcode.FAIL, err), https.StatusInternalServerError)
		return
	}
	reportResultColumns, err := h.ReportResultColumnSrv.GetByReportId(c, db, report.ReportId)
	if err != nil {
		gins.Err(c, ferror.WrapWithCode("报表返回结果获取失败", resultcode.FAIL, err), https.StatusInternalServerError)
		return
	}
	result := GetReportResult{}
	result.PageSupport = report.PageSupport
	result.DisplayType = report.DisplayType
	result.ShowSummary = report.ShowSummary
	result.Forms = make([]GetReportResultForm, 0)
	result.Results = make([]GetReportResultColumn, 0)
	for _, reportForm := range reportForms {

		form := GetReportResultForm{
			FormName:        reportForm.Name,
			FormType:        reportForm.Type,
			AttributeName:   reportForm.AttributeName,
			ExtraConfig:     reportForm.ExtraConfig,
			IndexNum:        reportForm.IndexNum,
			DefaultValue:    reportForm.DefaultValue,
			Required:        reportForm.Required,
			QueryReportCode: reportForm.QueryReportCode,
		}
		if reportForm.DictCategoryId != nil && *reportForm.DictCategoryId != "" && reportForm.ReturnAllDict {
			dicts, err := h.DictSrv.DictMapByCategoryId(c, *reportForm.DictCategoryId)
			if err != nil {
				gins.Err(c, ferror.WrapWithCode("获取字典列表失败", resultcode.FAIL, err), https.StatusInternalServerError)
				return
			}
			ds := []DictInfo{}
			for k, v := range dicts {
				ds = append(ds, DictInfo{
					Text:  v,
					Value: k,
				})
			}
			form.Dicts = ds
		}
		result.Forms = append(result.Forms, form)

	}
	for _, resultColumn := range reportResultColumns {
		column := GetReportResultColumn{
			ResultName:          resultColumn.Name,
			ResultType:          resultColumn.Type,
			AttributeName:       resultColumn.AttributeName,
			IsShow:              resultColumn.IsShow,
			ExtraConfig:         resultColumn.ExtraConfig,
			IndexNum:            resultColumn.IndexNum,
			EmptyValueFontColor: resultColumn.EmptyValueFontColor,
			EmptyValue:          resultColumn.EmptyValue,
			FontColor:           resultColumn.FontColor,
			IsJump:              resultColumn.IsJump,
			JumpType:            resultColumn.JumpType,
			JumpTarget:          resultColumn.JumpTarget,
			JumpParams:          make([]*GetReportResultColumnJumpParam, 0),
			JumpMode:            resultColumn.JumpMode,
		}
		if resultColumn.JumpParams != nil {
			jumpParams := make([]*model.ReportResultColumnJumpParam, 0)
			bytes, err := resultColumn.JumpParams.MarshalJSON()
			if err != nil {
				gins.Err(c, ferror.WrapWithCode("序列化跳转参数异常", resultcode.FAIL, err), https.StatusInternalServerError)
				return
			}
			err = json.Unmarshal(bytes, &jumpParams)
			if err != nil {
				gins.Err(c, ferror.WrapWithCode("序列化跳转参数异常", resultcode.FAIL, err), https.StatusInternalServerError)
				return
			}

			for _, param := range jumpParams {
				column.JumpParams = append(column.JumpParams, &GetReportResultColumnJumpParam{
					ParamType: param.ParamType,
					Name:      param.Name,
					Value:     param.Value,
				})
			}
		}
		result.Results = append(result.Results, column)

	}

	gins.Suc(c, result)
}
